package com.hiray.wanandroid.data

import androidx.lifecycle.ViewModel
import androidx.lifecycle.asFlow
import androidx.lifecycle.liveData
import androidx.lifecycle.viewModelScope
import androidx.paging.Pager
import androidx.paging.PagingConfig
import androidx.paging.PagingData
import com.hiray.wanandroid.net.ApiHelper
import com.hiray.wanandroid.net.apiCall
import com.hiray.wanandroid.net.response.PublicArticle
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.flow.Flow

class PublicViewModel : ViewModel() {
    fun publicArticleListFlow(id: String): Flow<PagingData<PublicArticle>> {
        return Pager(PagingConfig(20)) { PublicArticleSource(id) }.flow
    }

    val publicListFlow = liveData(viewModelScope.coroutineContext + Dispatchers.IO) {
        val publicList = apiCall { ApiHelper.api().fetchPublicList() }
        if (publicList.isSuccess)
            emit(publicList.data)
    }.asFlow()
}